# dmitry.a.konovalov@gmail.com dmitry.konovalov@jcu.edu.au
# 
#http://mad-scientist.net/make/autodep.html
#http://locklessinc.com/articles/makefile_tricks/

#We don't need to clean up when we're making these targets
NODEPS:=clean
# Add .d to Make's recognized suffixes.
SUFFIXES += .d


# UNIT setup ====== START ======
# ISSUE!!! order of compiling is not fix and .mod may not be ready when needed
SRCS  := sys_setup_mod.f95 dbg_mod.f95 test_mod.f95
#SRCS  := sys_setup_mod.f95 dbg_mod.f95 test_mod.f95 vec_mod.f95 vec_factory.f95 grid_mod.f95 \
#  func_factory.f95
SRCS  := $(addprefix $(SRC_DIR)/, $(SRCS))
# the rest of src files
#Find all the source files in the src directory
SRCS2  := $(wildcard $(SRC_DIR)/*.$(SRC_EXT))
SRCS += $(SRCS2) 
OBJS  := $(SRCS:.$(SRC_EXT)=.o)
OBJS  := $(notdir $(OBJS))
OBJS  := $(addprefix $(OBJ_DIR)/, $(OBJS))
# [26-11-2012] given up on generating dependencies; too hard
#DEPS  := $(OBJS:.o=.d)
MODS  := $(OBJS:.o=.mod)
# UNIT setup ====== END ======

# ignore file named 'all'?
.PHONY: all clean

# dealing with gfortran bug
%.o : %.mod

$(TRGT) : $(OBJS) $(MODS)
	@echo "(TRGT) : (OBJS)"
	@echo "  TO  =(TRGT)=" "$@"
	@echo "  FROM=(OBJS)=" "$<"
	ar cr ${TRGT} ${OBJS} 
	ranlib ${TRGT}
	@echo "  ok"

    
#Don't create dependencies when we're cleaning, for instance
ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS))))
    #Chances are, these files don't exist.  GMake will create them and
    #clean up automatically afterwards
#    -include $(DEPS)
endif
#include $(wildcard *.d)


#This rule does the compilation
$(OBJ_DIR)/%.o $(OBJ_DIR)/%.mod:  $(SRC_DIR)/%.$(SRC_EXT) 
	@echo ".o :  .(SRC_EXT)  .d"
	@echo "  TO  =.o=" "$@"
	@echo "  FROM=.(SRC_EXT)  .d=" "$<"
	${CF} $(CFLAGS) -c $< -o $@ -J $(OBJ_DIR) 
	@echo "  ok"; 


#http://stackoverflow.com/questions/313778/generate-dependencies-for-a-makefile-for-a-project-in-c-c
#This is the rule for creating the dependency files
#$(SRC_DIR)/%.d: $(SRC_DIR)/%.$(SRC_EXT)
#	@echo ".d: .(SRC_EXT)"
#	@echo "  TO  =.d=" "$@"
#	@echo "  FROM=.(SRC_EXT)=" "$<"
#	${CF} $(DEP_FLAGS)  $<  -MF $@ 
#	@echo "  ok"
#	cat $@	
    
#http://www.chemie.fu-berlin.de/chemnet/use/info/make/make_5.html#SEC42
#To ignore errors in a command line, write a `-' at the beginning of the line's text (after the initial tab). The `-' is discarded before the command is passed to the shell for execution.
clean: 
	-${RM_FILES}  $(OBJ_DIR)/*.o  $(OBJ_DIR)/*.mod  $(TRGT)
	
	
	
# What I would like my makefile to do would be to compile all .cpp files in the /src folder to .o files in the /obj folder, then link all the .o files in /obj into the output binary in the root folder /project
#http://stackoverflow.com/questions/2908057/makefiles-compile-all-cpp-files-in-src-to-os-in-obj-then-link-to-binary
